#include"stack.h"

void StackInit(Stack* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;

}

bool IsEmpty(Stack* ps)
{
	return ps->top==0;
}

void StackPush(Stack* ps, STDataType data)
{
	assert(ps);
	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity*sizeof(STDataType));
		if (tmp != NULL)
		{
			ps->a = tmp;
		}
		ps->capacity = newcapacity;

	}
	ps->a[ps->top] = data;
	ps->top++;

}


void StackPop(Stack* ps)
{
	assert(ps);
	assert(!IsEmpty(ps));

	ps->top--;

}

STDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(!IsEmpty(ps));

	return ps->a[ps->top - 1];
}


int StackSize(Stack* ps)
{
	assert(ps);
	if (IsEmpty(ps))
	{
		return 0;
	}
	return ps->top - 1;

}


void StackDestroy(Stack* ps)
{
	assert(ps);
	
	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->top = 0;

}